﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Telerik.Sitefinity;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity.Blogs.Model;
using Telerik.Sitefinity.Modules.Blogs;
using Telerik.Sitefinity.GenericContent.Model;
using Telerik.Sitefinity.Workflow;
using System.Globalization;

namespace Migration.Classes
{
	public static class MigrationBlogs
	{
		private static BlogsManager m_BlogsManager;

		static MigrationBlogs()
		{
			m_BlogsManager = BlogsManager.GetManager(MigrationSettings.BlogsProvider);
		}

		public static void CheckManagers()
		{
			if (m_BlogsManager.Provider == null)
			{
				m_BlogsManager = BlogsManager.GetManager(MigrationSettings.BlogsProvider);
			}
		}

		public static void ImportBlog(Telerik.Sitefinity.Services.Migration.MigrationBlog blogContent)
		{
			CheckManagers();

			Guid id = blogContent.Id;
			string name = blogContent.Name;

			Blog blogItem;
			blogItem = m_BlogsManager.GetBlogs().Where(t => t.Id == id).FirstOrDefault();
			if (blogItem == null)
			{
				blogItem = m_BlogsManager.CreateBlog(id);
			}

			MigrationLogger.AppendLogMessage(String.Format("Importing blog \"<b>{0}</b>\"...<br/>", name));

			blogItem.Description[MigrationCultures.DefaultCulture] = blogContent.Description;
			blogItem.DateCreated = blogContent.DateCreated;
			blogItem.LastModified = blogContent.DateCreated;
			blogItem.PublicationDate = blogContent.DateCreated;
			blogItem.Owner = MigrationUsers.DefaultOwner;
			blogItem.Title[MigrationCultures.DefaultCulture] = name;
			blogItem.UrlName[MigrationCultures.DefaultCulture] = MigrationUtils.GetUrlName(name);

			m_BlogsManager.RecompileItemUrls<Blog>(blogItem);
			m_BlogsManager.SaveChanges();

			foreach (Telerik.Sitefinity.Services.Migration.MigrationGenericContent blogContentPost in blogContent.Posts)
			{
				var language = blogContentPost.Language;
                var culture = new CultureInfo(language);
				string blogPostTitle = String.Empty;

				Guid postId = blogContentPost.Id;
				bool addNewLanguage = false;
				BlogPost checkPost = m_BlogsManager.GetBlogPosts().Where(t => t.Id == postId).FirstOrDefault();
				if (checkPost != null)
				{
					if (MigrationCultures.IsMultilingual)
					{
						if (checkPost.AvailableLanguages.Contains(language))
						{
							MigrationLogger.AppendLogMessage(MigrationUtils.GetLocalizableSkipMessage(checkPost.Title, blogContentPost.Language) + "<br/>");
							continue;
						}
						else
							addNewLanguage = true;
					}
					else
					{
						MigrationLogger.AppendLogMessage(MigrationUtils.GetLocalizableSkipMessage(checkPost.Title, String.Empty) + "<br/>");
						continue;
					}
				}

				BlogPost blogPost;
				if (addNewLanguage)
					blogPost = checkPost;
				else
					blogPost = m_BlogsManager.CreateBlogPost(postId);

				blogPost.Parent = blogItem;
				string blogPostText = String.Empty;
				if (blogContentPost.Content != null)
				{
					blogPostText = blogContentPost.Content.ToString();
				}
				blogPostText = MigrationUrlRewriter.RewriteAlbumUrls(blogPostText);

				if (String.IsNullOrEmpty(language))
					blogPost.Content = blogPostText;
				else
					blogPost.SetString("Content", blogPostText, language);

				foreach (KeyValuePair<string, object> metaData in blogContentPost.MetaData)
				{
					if (metaData.Value == null)
						continue;

					switch (metaData.Key)
					{
						case "Author":
							break;
						case "BlogID":
							break;
						case "Category":
                            MigrationTaxonomies.AddCategoryToOrganizer(metaData.Value.ToString(), blogPost.Organizer, culture);
							break;
						case "Publication_Date":
							blogPost.PublicationDate = DateTime.Parse(metaData.Value.ToString());
							break;
						case "Title":
							if (String.IsNullOrEmpty(language))
								blogPost.Title = blogPostTitle = metaData.Value.ToString();
							else
								blogPost.Title[culture] = blogPostTitle = metaData.Value.ToString();
							break;
						case "View_Count":
							blogPost.ViewsCount = Int32.Parse(metaData.Value.ToString());
							break;
						default:
						{
							string metaDataName = metaData.Key;
							var checkField = App.WorkWith().DynamicData().Type(typeof(BlogPost)).Fields().Get().Where(f => f.FieldName == metaDataName).FirstOrDefault();
							if (checkField != null)
							{
								try
								{
									blogPost.SetValue(metaDataName.ToLowerInvariant(), metaData.Value.ToString());
								}
								catch (NullReferenceException) { };
							}
						}
						break;
					}
				}

                // Add the URL name
				var urlName = String.Empty;
				if (String.IsNullOrEmpty(language))
					urlName = MigrationUtils.GetUrlName(blogPost.Title);
				else
					urlName = MigrationUtils.GetUrlName(blogPost.Title[culture]);

                var checkUrl = m_BlogsManager.GetBlogPosts().Where(t => t.UrlName == urlName).FirstOrDefault();
                if (checkUrl != null)
                    urlName = MigrationUtils.GetUrlName(blogPost.Id.ToString());

				if (String.IsNullOrEmpty(language))
				    blogPost.UrlName = urlName;
				else
                    blogPost.UrlName[culture] = urlName;

				blogPost.DateCreated = blogContentPost.DateCreated;
				blogPost.LastModified = blogContentPost.DateModified;
				blogPost.Owner = MigrationUsers.DefaultOwner;

				// Add the tags
                MigrationTaxonomies.AddTagsToOrganizer(blogContentPost.Tags, blogPost.Organizer, culture);

				var masterId = blogPost.OriginalContentId;

				m_BlogsManager.RecompileItemUrls<BlogPost>(blogPost);

				if (blogPost.Status == ContentLifecycleStatus.Master)
				{
					masterId = blogPost.Id;
				}

				m_BlogsManager.SaveChanges();

				var contextBag = new Dictionary<string, string>();
				contextBag.Add("ContentType", blogPost.GetType().FullName);
				var publicationDate = blogPost.PublicationDate;

				WorkflowManager.MessageWorkflow(
					masterId,
					blogPost.GetType(),
					MigrationSettings.GenericContentProvider,
					"Publish",
					false,
					contextBag);

				// Add the comments
				MigrationComments.AddCommentsToBlogPost(blogPost.Id, blogContentPost.Comments, language);

				MigrationLogger.AppendLogMessage(MigrationUtils.GetLocalizableImportMessage(blogPostTitle, blogContentPost.Language) + "<br/>");
			}
		}
	}
}
